package com.yunkss.eftool.controller;

import com.yunkss.eftool.business.result.EfResult;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * @Author csx
 * @Date 2024/5/10 11:34
 * @Description TODO  UploadController  上传控制器
 **/
@RestController
@RequestMapping("/eftool")
public class UploadController {

    private static final Path BASE_PATH = Paths.get("./uploads");

//    @PostMapping("/upload")
//    public Mono<List<String>> upload(@RequestPart("file") Flux<FilePart> files) {
//        return files.flatMap(filePart -> {
//            String fileName = UUID.randomUUID() + "-" + filePart.filename();
//            final Path path = BASE_PATH.resolve(fileName);
//            final File dest = path.toFile();
//            return filePart.transferTo(dest).thenReturn(dest.getName());
//        }).collectList();
//    }

    @PostMapping("/upload")
    public Mono<EfResult<String>> upload(@RequestPart("file") FilePart filePart) {
        String fileName = UUID.randomUUID() + "-" + filePart.filename();
        final Path path = BASE_PATH.resolve(fileName);
        final File dest = path.toFile();
        Mono<String> stringMono = filePart.transferTo(dest).thenReturn(dest.getName());
        return stringMono.map(item -> EfResult.success("上传成功~", item));
    }

    @GetMapping("/download/{fileName:.+}")
    public Mono<ResponseEntity<Resource>> downloadFile(@PathVariable String fileName) throws MalformedURLException {
        Resource resource = new UrlResource(BASE_PATH.resolve(fileName).normalize().toUri());
        return Mono.fromSupplier(() -> {
            try {
                if (resource.exists() && resource.isReadable()) {
                    String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
                    long contentLength = resource.contentLength();

                    byte[] data = FileCopyUtils.copyToByteArray(resource.getInputStream());
                    ByteArrayResource byteArrayResource = new ByteArrayResource(data);

                    return ResponseEntity.ok()
                            .contentType(MediaType.parseMediaType(contentType))
                            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                            .contentLength(contentLength)
                            .body(byteArrayResource);
                } else {
                    return ResponseEntity.notFound().build();
                }
            } catch (IOException e) {
                throw new RuntimeException("下载文件时出现错误", e);
            }
        });
    }



}
